use crate::modules::interfaces::{RouteRuleInterface, GatewayConfigInterface};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::time;
use ::time::OffsetDateTime;



pub struct GatewayService {
    pub route_rules: Arc<RwLock<HashMap<i32, RouteRuleInterface>>>,
    pub gateway_configs: Arc<RwLock<HashMap<String, GatewayConfigInterface>>>,
    pub hot_reload_enabled: Arc<RwLock<bool>>,
    pub last_reload_time: Arc<RwLock<OffsetDateTime>>,
}

impl GatewayService {
    pub fn new(config: &crate::config::GatewayConfig) -> Self {
        println!("使用配置初始化网关服务: {:?}", config);
        
        let service = Self {
            route_rules: Arc::new(RwLock::new(HashMap::new())),
            gateway_configs: Arc::new(RwLock::new(HashMap::new())),
            hot_reload_enabled: Arc::new(RwLock::new(true)),
            last_reload_time: Arc::new(RwLock::new(OffsetDateTime::now_utc())),
        };
        
        // 根据配置设置默认参数
        if let Ok(mut enabled) = service.hot_reload_enabled.try_write() {
            *enabled = config.enable_circuit_breaker;
        }
        
        service
    }

    pub async fn list_route_rules(&self) -> Vec<RouteRuleInterface> {
        let rules = self.route_rules.read().await;
        rules.values().cloned().collect()
    }

    pub async fn add_route_rule(&self, rule: RouteRuleInterface) -> Result<(), Box<dyn std::error::Error>> {
        let mut rules = self.route_rules.write().await;
        if rules.contains_key(&rule.id) {
            return Err("Route rule with this ID already exists".into());
        }
        rules.insert(rule.id, rule);
        Ok(())
    }

    pub async fn get_route_rule(&self, id: i32) -> Option<RouteRuleInterface> {
        let rules = self.route_rules.read().await;
        rules.get(&id).cloned()
    }

    pub async fn update_route_rule(&self, id: i32, rule: RouteRuleInterface) -> Result<(), Box<dyn std::error::Error>> {
        let mut rules = self.route_rules.write().await;
        if rules.contains_key(&id) {
            rules.insert(id, rule);
            Ok(())
        } else {
            Err("Route rule not found".into())
        }
    }

    pub async fn delete_route_rule(&self, id: i32) -> Result<(), Box<dyn std::error::Error>> {
        let mut rules = self.route_rules.write().await;
        rules.remove(&id);
        Ok(())
    }

    pub async fn add_gateway_config(&self, config: GatewayConfigInterface) -> Result<(), Box<dyn std::error::Error>> {
        let mut configs = self.gateway_configs.write().await;
        configs.insert(config.config_key.clone(), config);
        Ok(())
    }

    pub async fn list_gateway_configs(&self) -> Vec<GatewayConfigInterface> {
        let configs = self.gateway_configs.read().await;
        configs.values().cloned().collect()
    }

    pub async fn get_gateway_config(&self, key: &str) -> Option<GatewayConfigInterface> {
        let configs = self.gateway_configs.read().await;
        configs.get(key).cloned()
    }

    pub async fn update_gateway_config(&self, key: &str, config: GatewayConfigInterface) -> Result<(), Box<dyn std::error::Error>> {
        let mut configs = self.gateway_configs.write().await;
        if configs.contains_key(key) {
            configs.insert(key.to_string(), config);
            Ok(())
        } else {
            Err("Gateway config not found".into())
        }
    }

    pub async fn delete_gateway_config(&self, key: &str) -> Result<(), Box<dyn std::error::Error>> {
        let mut configs = self.gateway_configs.write().await;
        configs.remove(key);
        Ok(())
    }

    // 热加载相关方法
    pub async fn enable_hot_reload(&self) {
        let mut enabled = self.hot_reload_enabled.write().await;
        *enabled = true;
        println!("热加载功能已启用");
    }

    pub async fn disable_hot_reload(&self) {
        let mut enabled = self.hot_reload_enabled.write().await;
        *enabled = false;
        println!("热加载功能已禁用");
    }

    pub async fn is_hot_reload_enabled(&self) -> bool {
        let enabled = self.hot_reload_enabled.read().await;
        *enabled
    }

    pub async fn get_last_reload_time(&self) -> OffsetDateTime {
        let time = self.last_reload_time.read().await;
        *time
    }

    /// 手动触发配置重载
    pub async fn trigger_reload(&self) -> Result<(), Box<dyn std::error::Error>> {
        if !self.is_hot_reload_enabled().await {
            return Err("热加载功能未启用".into());
        }

        println!("手动触发配置重载...");
        self.update_last_reload_time().await;
        Ok(())
    }

    /// 批量更新路由规则（用于热加载）
    pub async fn batch_update_route_rules(&self, new_rules: Vec<RouteRuleInterface>) -> Result<(), Box<dyn std::error::Error>> {
        let mut rules = self.route_rules.write().await;
        rules.clear();
        
        for rule in new_rules {
            rules.insert(rule.id, rule);
        }

        self.update_last_reload_time().await;
        println!("路由规则已批量更新，共 {} 条规则", rules.len());
        Ok(())
    }

    /// 批量更新网关配置（用于热加载）
    pub async fn batch_update_gateway_configs(&self, new_configs: Vec<GatewayConfigInterface>) -> Result<(), Box<dyn std::error::Error>> {
        let mut configs = self.gateway_configs.write().await;
        configs.clear();
        
        for config in new_configs {
            configs.insert(config.config_key.clone(), config);
        }

        self.update_last_reload_time().await;
        println!("网关配置已批量更新，共 {} 条配置", configs.len());
        Ok(())
    }

    /// 启动热加载监听器
    pub async fn start_hot_reload_listener(&self, check_interval: Duration) {
        let service = self.clone();
        
        tokio::spawn(async move {
            let mut interval = time::interval(check_interval);
            
            loop {
                interval.tick().await;
                
                if service.is_hot_reload_enabled().await {
                    // 检查配置是否有更新（这里可以扩展为检查文件变化或数据库变化）
                    // 目前先记录日志，实际应用中可以实现文件监听或数据库轮询
                    println!("热加载监听器运行中...");
                }
            }
        });
    }

    async fn update_last_reload_time(&self) {
        let mut time = self.last_reload_time.write().await;
        *time = OffsetDateTime::now_utc();
    }

    pub async fn get_active_gateway_configs(&self) -> Vec<GatewayConfigInterface> {
        let configs = self.gateway_configs.read().await;
        configs.values().filter(|c| c.is_active).cloned().collect()
    }
}

impl Clone for GatewayService {
    fn clone(&self) -> Self {
        Self {
            route_rules: self.route_rules.clone(),
            gateway_configs: self.gateway_configs.clone(),
            hot_reload_enabled: self.hot_reload_enabled.clone(),
            last_reload_time: self.last_reload_time.clone(),
        }
    }
}